import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Row,
  Col,
  Input,
  Button,
  Divider,
  Drawer,
  Select,
  Popconfirm,
  message,
  Modal,
} from 'antd';
import { connect } from 'dva';
import { useAntdTable } from '@umijs/hooks';
import SlickTable from '@/components/SlickTable';
import { getPageSizeByCardHeight } from '@/utils/utils';
import request from '@/utils/request';
import Operpage from './components/Operpage';

const { Option } = Select;

const namespace = 'abnormalConfig';

function AbnormalConfig({ size: { height }, form, dispatch }) {
  const { getFieldDecorator } = form;

  const [size, setSize] = useState(getPageSizeByCardHeight(height - 64 - 8));
  const [paramsObj, setParamsObj] = useState({});
  // 右抽屉显示隐藏控制
  const [visible, setVisible] = useState(false);
  // 状态 add 、 detail 、 edit
  const [status, setStatus] = useState('');
  const [orderFromMap, setOrderFrom] = useState([]);
  const [exceptionTypeMap, setExceptionType] = useState([]);

  // 通过dva存当前需要传递的数据
  const savePassData = params => {
    dispatch({
      type: `${namespace}/savePassData`,
      payload: params,
    });
  };

  const handleEffect = record => {
    Modal.confirm({
      content: '确定要删除吗?',
      onOk() {
        request('pmc/pms/ExceptionOrdController/delete', {
          data: { exeptionModelId: record.exeptionModelId },
          method: 'POST',
        }).then(res => {
          if (res) {
            refresh();
          } else {
            message.error('删除失败！');
          }
        });
      },
    });
  };

  useEffect(() => {
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'orderFrom',
      },
    }).then(res => {
      setOrderFrom(res);
    });
    request('pmc/pms/StaticDataController/getStaticAttr.do', {
      data: {
        busiObjNbr: 'OrderExceptionModel',
        attrNbr: 'exceptionType',
      },
    }).then(res => {
      setExceptionType(res);
    });
  }, []);

  const getTableData = ({ current, pageSize, paramsObj }) => {
    return request('pmc/pms/ExceptionOrdController/queryPage', {
      data: {
        pageNum: current,
        pageSize: pageSize,
        sortName: '',
        sortOrder: 'asc',
        ...paramsObj,
      },
    }).then(res => {
      if (Array.isArray(res.data.records)) {
        return {
          total: res.data.total,
          data: res.data.records.map(val => {
            const { children, ...rest } = val;
            return rest;
          }),
        };
      }
      return {
        total: 0,
        data: [],
      };
    });
  };

  const { tableProps, refresh } = useAntdTable(
    params => {
      return getTableData({ ...params, pageSize: size, paramsObj });
    },
    [paramsObj, height],
    {
      defaultPageSize: size,
      form,
    }
  );
  const { pagination, ...restTableProps } = tableProps;

  useEffect(() => {
    setSize(getPageSizeByCardHeight(height - 64 - 8));
  }, [height]);

  const submit = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      // console.log(fieldsValue);
      setParamsObj({
        ...fieldsValue,
      });
    });
  };

  const handleOper = (status, record) => {
    setStatus(status);
    setVisible(true);
    savePassData(record);
  };

  const onClose = () => {
    setVisible(false);
  };

  const handleReset = () => {
    form.resetFields();
  };

  const columns = [
    {
      title: '系统来源',
      dataIndex: 'orderFromName',
      width: 120,
      ellipsis: true,
    },
    {
      title: '异常名称',
      dataIndex: 'exceptionModelName',
      ellipsis: true,
    },
    {
      title: '异常编码',
      dataIndex: 'exceptionCode',
      ellipsis: true,
    },
    {
      title: '异常分类',
      dataIndex: 'exceptionTypeName',
      ellipsis: true,
      width: 100,
      align: 'center',
    },
    {
      title: '关键字',
      dataIndex: 'exceptionKey',
      ellipsis: true,
    },
    {
      title: '异常原因',
      dataIndex: 'exceptionReason',
      ellipsis: true,
    },
    {
      title: '异常提示语',
      dataIndex: 'exceptionTips',
      ellipsis: true,
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                handleOper('edit', record);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleEffect(record);
              }}
            >
              删除
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <>
      <Card
        title="异常配置管理列表"
        style={{ minHeight: height }}
        className="cute"
        extra={
          <Button
            type="primary"
            onClick={() => {
              handleOper('add', {});
            }}
          >
            新增
          </Button>
        }
      >
        <Form className="flow fix-label padding-bottom">
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="系统来源">
                {getFieldDecorator('orderFrom')(
                  <Select allowClear placeholder="请选择">
                    {orderFromMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常分类">
                {getFieldDecorator('exceptionType')(
                  <Select allowClear placeholder="请选择">
                    {exceptionTypeMap.map(item => {
                      return (
                        <Select.Option value={item.attrValue}>{item.attrValueName}</Select.Option>
                      );
                    })}
                  </Select>
                )}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常名称">
                {getFieldDecorator('exceptionModelName')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="异常编码">
                {getFieldDecorator('exceptionCode')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="异常关键字">
                {getFieldDecorator('exceptionKey')(<Input allowClear placeholder="请输入" />)}
              </Form.Item>
            </Col>
            <Col span={18} className="text-right">
              <Button type="primary" onClick={submit}>
                查询
              </Button>
              <Button className="margin-left" onClick={handleReset}>
                重置
              </Button>
            </Col>
          </Row>
        </Form>
        <SlickTable
          style={{ marginTop: 8 }}
          rowKey={record => record.exeptionModelId}
          columns={columns}
          {...restTableProps}
          data={{
            pagination: {
              ...pagination,
              pageSize: size,
            },
          }}
        />
      </Card>
      <Drawer
        title={
          status === 'add' ? '新增异常配置' : status === 'edit' ? '异常配置修改' : '异常配置详情'
        }
        destroyOnClose
        width={680}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
      >
        <Operpage
          close={onClose}
          refresh={refresh}
          disabled={status === 'detail' ? true : false}
          status={status}
        />
      </Drawer>
    </>
  );
}

export default connect(({ setting }) => ({
  size: setting.size,
}))(Form.create()(AbnormalConfig));
